package org.anyline.dash;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

import java.util.Arrays;

public class PooledDashScopeObjectUsage {
    public static void main(String[] args) throws Exception {
        PooledDashScopeObjectFactory pooledDashScopeObjectFactory =
            new PooledDashScopeObjectFactory();
        GenericObjectPoolConfig<Generation> config = new GenericObjectPoolConfig<>();
        config.setMaxTotal(32);
        config.setMinIdle(32);
        GenericObjectPool<Generation> generationPool =
            new GenericObjectPool<>(pooledDashScopeObjectFactory, config);
        Generation gen = null;
        try {
            Message systemMsg = Message.builder().role(Role.SYSTEM.getValue())
                .content("You are a helpful assistant.").build();
            Message userMsg = Message.builder().role(Role.USER.getValue()).content("你好").build();
            GenerationParam param = GenerationParam.builder().model("qwen-plus")
                .messages(Arrays.asList(systemMsg, userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE).topP(0.8).enableSearch(true)
                .build();
            gen = generationPool.borrowObject();
            GenerationResult result = gen.call(param);
            System.out.println(result);
        } finally {
            if (gen != null) {
                generationPool.returnObject(gen);
            }
        }
        System.out.println("completed");
        generationPool.close();
    }

}
